import logging

from fastapi import APIRouter, Query

from app.controllers.menu import menu_controller
from app.schemas.base import Fail, Success, SuccessExtra
from app.schemas.menus import *

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/list", summary="获取菜单列表")
async def list_menu(page: int = Query(1, description="页码"),
                    page_size: int = Query(10, description="每页数量")):
    """
    获取菜单列表
    """
    parent_menus = await menu_controller.model.filter(parent_id=0
                                                      ).order_by("order")
    res_menus = []
    for menu in parent_menus:
        child_menu = await menu_controller.model.filter(parent_id=menu.id
                                                        ).order_by("order")
        menu_dict = await menu.to_dict()
        menu_dict["children"] = [await obj.to_dict() for obj in child_menu]
        res_menus.append(menu_dict)
    return SuccessExtra(data=res_menus,
                        total=len(res_menus),
                        page=page,
                        page_size=page_size)


@router.post("create", summary="创建菜单")
async def create_menu(menu_in: MenuCreate):
    """
    创建菜单
    """
    menu = await menu_controller.create(obj_in=menu_in)
    return Success(msg="create_menu创建成功")


@router.post("update", summary="更新菜单")
async def update_menu(menu_in: MenuUpdate):
    await menu_controller.update(id=menu_in.id, obj_in=menu_in.update_dict())
    return Success(msg="update_menu更新成功")


@router.post("delete", summary="删除菜单")
async def delete_menu(id: int = Query(..., description="菜单id")):
    child_menu_count = await menu_controller.model.filter(parent_id=id).count()
    if child_menu_count > 0:
        return Fail(msg="该菜单下有子菜单，无法删除")
    await menu_controller.remove(id=id)
    return Success(msg="delete_menu删除成功")
